
grApp.controller('CalendarDemoCtrl',['$scope', 'SginDayFactory',function ($scope,sginDayFactory) {
    'use strict';
    var $modalconfirm =angular.element("#my-confirm");

    //变量初始化
    $scope.MonthSignDay; //月度签到天数
    $scope.AllSignDays; //累计签到天数

    $scope.ClickDate; //点击的天数到日期

    $scope.GiftArray = [];
    $scope.load = function () {
        var progress = $.AMUI.progress;
        var $modal = angular.element("#my-modal-loading");
        progress.start();
        $modal.modal();
        //页面获取数据
        sginDayFactory.getSginDayValue().then(function (result) {
            $scope.MonthSignDay = result.MonthSignDay;
            $scope.AllSignDay = result.AllSignDay;
            $scope.AllSignDays = result.AllSignDays;
            $scope.SignState = result.SignState;
            $scope.GiftArray = result.GiftArray;
            $scope.UserPoint = result.point;
            $scope.firstSignDate=result.firstSignDate;
            $scope.lastSignDate=result.lastSignDate;
            progress.done();
            $modal.modal('close');
        });

    };
    $scope.load();
    $scope.loadEvents = function (date) {
        var date = date ||new Date();
        var events = [];
        var month = date.getMonth()+1;
        var year = date.getFullYear();
        //alert(year)
        console.log(month);
        sginDayFactory.getSginDayDetailValue(year,month).then(function(data){
            for (var i = 0; i < data.data.length; i += 1) {
                events.push({
                    title: '恭喜 - ' + '签到成功',
                    startTime: new Date(date.getFullYear(),date.getMonth(),data.data[i]+1),
                    endTime: new Date(date.getFullYear(),date.getMonth(),data.data[i]+1),
                    allDay: true
                });
            }
        }).finally(function(){
            $scope.eventSource = events;
        });

    };

    $scope.getCurrentMonth = function(res){
        $scope.loadEvents(new Date(res));
    }
    $scope.getNowTime = function(res){
        $scope.loadEvents(new Date(res));
        $scope.ClickDate =res.toDateString();
        //alert(res.toLocaleString())
    }
    $scope.getRule = function(){
        sginDayFactory.getRules().then(function(data){
            var supply = data.supply;
            var sign = data.sign;
            var arraySign = new Array();
            supply.sort(function(a,b){
                return parseInt(a['points'])-parseInt(b['points']);
            });
            for(var key in sign){
                //console.log(key)
                sign[key]['keyNum'] = key.substring(1);
                arraySign.push(sign[key]);
            }
            console.log(arraySign)
            arraySign.sort(function(a,b){
                return a['keyNum']- b['keyNum'];
            })
            $scope.supplys = supply ;
            $scope.sign = arraySign ;
        });
    }
    //事件触发
    $scope.onEventSelected = function (event) {
        if(!event){
            //获取需要扣减的积分
            if(!( new Date($scope.ClickDate) - new Date() > 0)){
                //获取当前日期到首签日的天数，传入到方法中，得到需要扣减的积分
                //2015/11/12
                sginDayFactory.getLevelOfBQ($scope.ClickDate).then(function(res){
                    if($scope.UserPoint - res.point >=0){
                        if(res.code === 0){
                            ConfirmShow("提醒","补签将扣除"+res.point+'积分！确定补签吗？',false,res.point,new Date($scope.ClickDate));
                        }else{
                            AlertShow('提醒','不在本轮签到周期内，不能补签哦!',false);
                        }
                    }else{
                        AlertShow('提醒','积分不足，赶快去补充积分吧',false);
                    }
                });
            }else{
                AlertShow('提醒','还没到呢，记得来签到哦！',false);
                //alert('还没到呢，记得来签到哦！')
            }
        }
    };
    //签到按钮点击事件
    $scope.signBtn = function () {
        if ($scope.SignState == 0) {
            sginDayFactory.setSginDayAction().then(function (result) {

                if (result.code == 0) {
                    //是否满足签到规则
                    console.log("签到成功，是否满足礼物领取条件"+result.hasGift);
                    if(result.hasGift==1){
                        console.log("签到成功，满足礼物领取条件"+result.level);
                        sginDayFactory.getGifts(result.level).then(function(data){
                            console.log("success");
                            AlertShow("提醒","签到成功,礼物已发放,请查收！",true);
                        });
                    }else{
                        console.log("签到成功，不满足礼物领取条件");
                        AlertShow("提醒","签到成功",true);
                    }
                } else {
                    if(result.code == 1011){
                        AlertShow("提醒","你今天已经签到过了哦!",false);
                    }else{
                        AlertShow("提醒","签到失败.页面正在维护中."+result.code,true);
                    }
                }
            })
        }else{
            AlertShow("提醒","你今天已经签到过了哦!",false);
        }
        //alert模态框调用

    };
    var AlertShow= function (title,content,reload) {
        var $modalalert =angular.element("#my-alert");
        $scope.AlertTitle=title;
        $scope.AlertContent=content;
        $scope.reload=reload;
        $modalalert.modal({
            relatedTarget: this,
            onCancel: function(e) {
                if($scope.reload){
                    location.reload();
                }
            }
        });
    }
    var ConfirmShow= function (title,content,reload,points,date) {
        var $modalconfirm =angular.element("#my-confirm");
        $scope.ConfrimTitle=title;
        $scope.ConfirmContent=content;
        $scope.reload=reload;
        $scope.points = points;
        $scope.date = date;
        $modalconfirm.modal({
            relatedTarget: this,
            onConfirm: function (options) {
                //扣减积分
                //开始补签
                sginDayFactory.signDaySupply($scope.date,$scope.points).then(function(res){
                    console.log(res.level);
                    if(res.code === 0 ){
                        sginDayFactory.getGifts(res.level).then(function(data){
                            //console.log("success");
                            AlertShow("提醒","补签成功,礼物已发放,请查收！",true);
                        });
                    }else if(res.code === 100){

                        AlertShow("提醒","不再同一个周期内，不能补签哦！",false);
                    }else{
                        AlertShow("提醒","补签成功！",true);
                    }
                }).catch(function(err){
                    AlertShow("提醒","补签失败了，重新补签吧！",true);
                })
            },
            onCancel: function(e) {
                if($scope.reload){
                    location.reload();
                }
            }
        });
    }
}]);

//签到工厂
grApp.factory('SginDayFactory', ['$http', '$q', function ($http, $q) {
    var service = {};
    //进入页面获取数据
    service.getSginDayDetailValue = function (year,month) {
        var deferred = $q.defer(); // 声明延后执行，表示要去监控后面的执行
        $http({
            method: 'GET',
            url: '/activity/getSignDayDetailAjax',
            params: { Year:year,Month: month  }
        }).success(function (data, status, headers, config) {
            deferred.resolve(data);
        }).
            error(function (data, status, headers, config) {
                deferred.reject(data);
            });
        return deferred.promise;
    };
    service.getSginDayValue = function () {
        var deferred = $q.defer(); // 声明延后执行，表示要去监控后面的执行
        $http({
            method: 'GET',
            url: '/activity/getSignDayValueAjax',
        }).success(function (data, status, headers, config) {
            deferred.resolve(data);
        }).
            error(function (data, status, headers, config) {
                deferred.reject(data);
            });
        return deferred.promise;
    };
    //签到Ajax操作
    service.setSginDayAction = function () {
        var deferred = $q.defer(); // 声明延后执行，表示要去监控后面的执行
        $http({
            method: 'GET',
            url: '/activity/setSignDayActionAjax'
        }).success(function (data, status, headers, config) {
            deferred.resolve(data);
        }).
            error(function (data, status, headers, config) {
                deferred.reject(data);
            });
        return deferred.promise;
    };
    //领取奖品操作
    service.getGifts=function(level){
        var deferred = $q.defer(); // 声明延后执行，表示要去监控后面的执行
        $http({
            method: 'GET',
            url: '/activity/getGift',
            params: {level: level}
        }).success(function (data, status, headers, config) {
            deferred.resolve(data);
        }).
            error(function (data, status, headers, config) {
                deferred.reject(data);
            });
        return deferred.promise;
    };
    //返回扣除的积分
    service.getLevelOfBQ=function(date){
        var deferred = $q.defer(); // 声明延后执行，表示要去监控后面的执行
        $http({
            method: 'GET',
            url: '/activity/getLevelOfBQ',
            params: {date: date}
        }).success(function (data, status, headers, config) {
            deferred.resolve(data);
        }).
            error(function (data, status, headers, config) {
                deferred.reject(data);
            });
        return deferred.promise;
    };
    //扣减积分
    service.signDaySupply=function(date,point){
        var deferred = $q.defer(); // 声明延后执行，表示要去监控后面的执行
        $http({
            method: 'GET',
            url: '/activity/signDaySupply',
            params: {date:date,point: point}
        }).success(function (data, status, headers, config) {
            deferred.resolve(data);
        }).
            error(function (data, status, headers, config) {
                deferred.reject(data);
            });
        return deferred.promise;
    };
    //扣减积分
    service.getRules=function(){
        var deferred = $q.defer(); // 声明延后执行，表示要去监控后面的执行
        $http({
            method: 'GET',
            url: '/activity/getRules',
        }).success(function (data, status, headers, config) {
            deferred.resolve(data);
        }).
            error(function (data, status, headers, config) {
                deferred.reject(data);
            });
        return deferred.promise;
    };
    return service;

}]);